home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 7968 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.1 KB  |  75 lines

  1. Path: sierra.net!usenet
  2. From: T Colwell <snowbull@sierra.net>
  3. Newsgroups: comp.lang.c++
  4. Subject: Does this create memory leak?...
  5. Date: Thu, 15 Feb 1996 17:35:36 -0800
  6. Organization: Sierra-Net
  7. Message-ID: <3123DF68.1677@sierra.net>
  8. NNTP-Posting-Host: 204.94.232.59
  9. Mime-Version: 1.0
  10. Content-Type: text/plain; charset=us-ascii
  11. Content-Transfer-Encoding: 7bit
  12. X-Mailer: Mozilla 2.0 (WinNT; I)
  13.  
  14. The code which follows seams like it would create a memory leak.  The CAT class contains member pointers to 
  15. objects on the heap.  When you take an existing object at reassign it via an overridden assignment operator to 
  16. a second object of the same type, what happens to the data at the originally pointed-to address?  Here's what I 
  17. mean:
  18.  
  19. *****************************************************
  20.    #include <iostreams.h>
  21.  
  22.    class CAT
  23.    {
  24.        public:
  25.             CAT();    // default constructor
  26.             // copy constructor and destructor intentionally excluded!
  27.              int GetAge() const { return *itsAge; }
  28.              int GetWeight() const { return *itsWeight; }
  29.              void SetAge(int age) { *itsAge = age; }
  30.              CAT operator=(const CAT &);
  31.  
  32.         private:
  33.              int *itsAge;
  34.              int *itsWeight;
  35.    };
  36.  
  37.    CAT::CAT()
  38.    {
  39.         itsAge = new int;
  40.         itsWeight = new int;
  41.         *itsAge = 5;
  42.         *itsWeight = 9;
  43.    }
  44.  
  45.  
  46.   CAT CAT::operator=(const CAT & rhs)
  47.   {
  48.      if (this == &rhs)
  49.         return *this;
  50.         itsAge = new int;
  51.         itsWeight = new int;
  52.         *itsAge = rhs.GetAge();
  53.         *itsWeight = rhs.GetWeight();
  54.   }
  55.  
  56.  
  57.    void main()
  58.    {
  59.         CAT frisky;
  60.         frisky.SetAge(6);
  61.         CAT whiskers;
  62.         whiskers = frisky; // <--doesn't this leave
  63.                            // the old members of whiskers
  64.                            // stranded in the heap?
  65.    }
  66. **************************************************
  67.  
  68. The assignment operator reinitializes itsAge and itsWeight to point to new heap addresses, what happens to the 
  69. addresses they were pointing to before?  Doesn't this create stranded addresses (leaks)?
  70.  
  71.  
  72. Thanks in advance!
  73.  
  74. -Tyler Colwell
  75.